package com.yc.framework.manager;

import com.yc.common.utils.Threads;
import com.yc.common.utils.spring.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author ruoyi
 */
public class AsyncManager {

    private static final Logger log = LoggerFactory.getLogger(AsyncManager.class);
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 单例模式（延迟加载）
     */
    private static volatile AsyncManager instance;

    /**
     * 异步操作任务调度线程池
     */
    @Resource
    private ScheduledExecutorService executor;

    /**
     * 单例模式
     */
    private AsyncManager() {
        // 防止反射破坏单例
        if (instance != null) {
            throw new IllegalStateException("Instance already created");
        }
    }

    /**
     * 获取单例实例
     */
    public static AsyncManager getInstance() {
        if (instance == null) {
            synchronized (AsyncManager.class) {
                if (instance == null) {
                    instance = new AsyncManager();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化线程池
     */
    private void initExecutor() {
        if (executor == null) {
            try {
                executor = SpringUtil.getBean("scheduledExecutorService");
            } catch (Exception e) {
                log.error("Failed to initialize ScheduledExecutorService. Please check Spring context configuration.", e);
                throw new IllegalStateException("ScheduledExecutorService not found in Spring context", e);
            }
        }
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        initExecutor(); // 确保线程池已初始化
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        if (executor != null) {
            Threads.shutdownAndAwaitTermination(executor);
        }
    }
}